package com.itboye.lottery.app

import android.annotation.SuppressLint
import android.app.Activity
import android.app.ActivityManager
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.support.multidex.MultiDexApplication
import android.text.TextUtils
import com.itboye.lottery.utils.Const
import com.itboye.lottery.utils.CrashHandler
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import java.lang.ref.WeakReference
import java.util.*


/**
 * Created by Administrator on 2017/11/28.
 */
class MyApplication : MultiDexApplication() {

    var activityList: MutableList<WeakReference<Activity>> = LinkedList()

//    var mRetrofit: Retrofit? = null
//
//    var mIApi: RetrofitApi? = null
//
//    var mACache: ACache? = null
//
//    var loginInfo: LoginInfo? = null
//
//    var galleryConfig: GalleryConfig? = null
//    var mPushAgent: PushAgent? = null

    var role: String? = null
    var iwxapi: IWXAPI? = null

    companion object {
        var instance: MyApplication? = null
//        val items = listOf("apple", "banana", "kiwi", "apple", "banana", "kiwi", "apple", "apple", "banana", "kiwi", "apple", "banana", "kiwi", "apple", "apple", "banana", "kiwi", "apple", "banana", "kiwi", "apple") as List<String>
//        var cityDBManager: CityDBManager? = null
//        var addressDbHelper: AddressDbHelper? = null
    }

    override fun onCreate() {
        super.onCreate()
        instance = MyApplication@ this
        initCrashHandler()
        regWx()
        initCatchExceptionUtil()
        initRole()
//        clearImageDiskCache(applicationContext)
        initACache()
        //初始化数据库
        initCacheDb()
        initAddressDb()
        initUploadImageConfig()
        initUmeng()
    }

    private fun initCrashHandler() {
        val crashHandler = CrashHandler.getInstance()
        crashHandler.init(this)
    }

    private fun initCatchExceptionUtil() {
//        val crashHandler = CrashHandler.getInstance()
//        crashHandler.init(this)
    }


    private fun initAddressDb() {
//        cityDBManager = CityDBManager(this)
//        cityDBManager!!.openDateBase()
//        AddressDbHelper().initAddressDB()
//        addressDbHelper = AddressDbHelper.instance
    }

    private fun initRole() {
//        role
    }

    private fun initUmeng() {
//        mPushAgent = PushAgent.getInstance(applicationContext)
////注册推送服务，每次调用register方法都会回调该接口
//        mPushAgent!!.register(object : IUmengRegisterCallback {
//
//            override fun onSuccess(deviceToken: String) {
//                //注册成功会返回device token
//                Log.v(Const.TAG_DEBUG, "onSuccess-->$deviceToken")
//            }
//
//            override fun onFailure(s: String, s1: String) {
//                Log.v(Const.TAG_DEBUG, "onFailure-->s:$s S1:$s1")
//            }
//        })
//
//        MobclickAgent.setCatchUncaughtExceptions(true)
    }

    fun getTopActivity():Activity{
        var activityTop: Activity? = null
        for (activity in activityList) {
            if (activity.get() != null) {
                if (isForeground(applicationContext, activity.get()!!.javaClass.name)) {
                    activityTop = activity.get()
                }
            }

        }

        return activityTop!!
    }
    var dialog:Dialog?=null
    var count=0;
    fun showUpdateVersionDialog(msg:String){
//        var activity=getTopActivity()
//        var alertDialog:AlertDialog.Builder=AlertDialog.Builder(activity, android.R.style.Theme_DeviceDefault_Light_Dialog_Alert)
//        alertDialog.setMessage(msg)
//        alertDialog.create()
//        if (dialog!=null) {
//            if (dialog!!.isShowing) {
//                dialog!!.dismiss()
//            }
//        }
//        if (!activity.isFinishing) {
//            if (count==0) {
//                dialog = alertDialog.show()
//            }else{
//                dialog!!.dismiss()
//                count=0
//            }
//            count++
//        }
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param context   Context
     * @param className 界面的类名
     * @return 是否在前台显示
     */
    fun isForeground(context: Context?, className: String): Boolean {
        if (context == null || TextUtils.isEmpty(className))
            return false
        @SuppressLint("WrongConstant") val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val list = am.getRunningTasks(1)
        if (list != null && list.size > 0) {
            val cpn = list[0].topActivity
            if (className == cpn.className)
                return true
        }
        return false
    }

    /**
     * 清除图片磁盘缓存
     */
    fun clearImageDiskCache(context: Context) {
//        try {
//            if (Looper.myLooper() === Looper.getMainLooper()) {
//                Thread(Runnable {
//                    Glide.get(context).clearDiskCache()
//                    // BusUtil.getBus().post(new GlideCacheClearSuccessEvent());
//                }).start()
//            } else {
//                Glide.get(context).clearDiskCache()
//            }
//        } catch (e: Exception) {
//            e.printStackTrace()
//        }

    }

    private fun initUploadImageConfig() {
//        galleryConfig = GalleryConfig.Builder()
//                .imageLoader(XGlideLoader())    // ImageLoader 加载框架（必填）
////                .iHandlerCallBack(iHandlerCallBack)     // 监听接口（必填）
//                .provider("com.yancy.gallerypickdemo.fileprovider")   // provider(必填)
////                .pathList(path)                         // 记录已选的图片
//                .multiSelect(false)                      // 是否多选   默认：false
//                .multiSelect(false, 9)                   // 配置是否多选的同时 配置多选数量   默认：false ， 9
////                .maxSize(9)                             // 配置多选时 的多选数量。    默认：9
//                .crop(false)                             // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
//                .crop(false, 1f, 1f, 500, 500)             // 配置裁剪功能的参数，   默认裁剪比例 1:1
//                .isShowCamera(true)                     // 是否现实相机按钮  默认：false
//                .filePath("/Gallery/Pictures")          // 图片存放路径
//                .build()
    }

    private fun initACache() {
//        mACache = ACache.get(this)
    }

    private fun initCacheDb() {
//        DBManager().init(applicationContext)
    }


    fun addActivity(activity: Activity) {
        activityList.add(WeakReference(activity))
    }


    fun removeAllActivity() {
        for (activity in activityList) {
            if (activity.get() != null) {
                activity.get()!!.finish()
            }
        }
    }

    fun regWx(): IWXAPI {
        iwxapi = WXAPIFactory.createWXAPI(applicationContext, Const.WX_APP_ID, false)
        iwxapi!!.registerApp(Const.WX_APP_ID)
        return iwxapi!!
    }

}